<template>
  <div class="app-container calendar-list-container" style="margin: 10px">
    <el-form :inline="true" :model="queryDataForm"  class="company-wrapper_search" @submit.native.prevent>
      <el-form-item label="登录名称">
        <el-input v-model="queryDataForm.username" placeholder="请输入登录名称" @keyup.enter.native="getList('noPage')"></el-input>
      </el-form-item>
      <!-- <el-form-item>
        <el-input v-model="queryDataForm.companyName" placeholder="公司名称"></el-input>
      </el-form-item> -->
      <el-form-item>
        <el-button @click="getList('noPage')"  type="primary">查询</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button
      @click="add"
      type="primary"
      v-if="this.$can('USER_ADD')"
    class="mtb15"
    >新增用户</el-button>
    <NbTable
      :tableHeaders="tableHeaders"
      :tableData="tableData"
      :clickData="clickData"
      :headerMap="queryMap"
      operatorFixed="left"
      operatorText
      height="auto"
      @clickRight="clickRight"
      :align="align"
    />
    <!-- 查询结果 -->
    <el-dialog title="修改密码" :visible.sync="dialogVisible" width="580px" :close-on-click-modal="false" class="change-title" :before-close="cancel">
      <el-form
        :inline="true"
        :model="resetDataForm"
        class="demo-form-inline change-pwd"
        :rules="rules"
        ref="ruleResetPwdForm"
      >
        <el-form-item label="新密码" prop="pwd" label-width="130px" style="width:90%;text-align:center;">
          <el-input v-model.trim="resetDataForm.pwd" placeholder="请输入新密码" clearable show-password></el-input>
        </el-form-item>
        <el-form-item label="再次输入新密码" prop="donePwd" label-width="130px" style="margin-bottom:30px;width:90%;text-align:center;">
          <el-input
            v-model.trim="resetDataForm.donePwd"
            placeholder="请输入新密码"
            clearable
            show-password
            
          ></el-input>
        </el-form-item>
        <p style="color:red;line-height:40px;position:absolute;top: 98px;left: 28%;font-size: 12px;" v-if="isShowError">两次密码不一致</p>
        <el-form-item style="text-align:center;width:100%;">
          <el-button type="primary" @click="doneResetPwd('ruleResetPwdForm')">保存</el-button>
          <el-button @click="cancel">放弃</el-button>
          
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分页 -->
    <el-pagination
      align="right"
      style="padding-top: 20px;margin-bottom:100px;"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="queryDataForm.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="queryDataForm.size"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
  </div>
</template>

<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 200px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
}

.scroll-content {
  background: #fff;
}
</style>

<script>
import md5 from 'md5'
import NbTable from '../../../components/nb-table'
export default {
  name: 'promotion',
  components: {
    NbTable
  },
  watch: {
    dialogVisible () {
      this.$nextTick(() => {
        this.$refs['ruleResetPwdForm'].resetFields()
      })
    }
  },
  data () {
    var validatePass = (rule, value, callback) => {
      value = value.replace(/[\u4e00-\u9fa5]/g, '')
      this.resetDataForm.pwd = value
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.resetDataForm.donePwd !== '') {
          this.$refs.ruleResetPwdForm.validateField('donePwd')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      value = value.replace(/[\u4e00-\u9fa5]/g, '')
      this.resetDataForm.donePwd = value
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.resetDataForm.pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      queryDataForm: {
        username: '',
        companyName: '',
        page: 1,
        size: 10
      },
      align: 'center',
      isShowError: false,
      dialogVisible: false,
      tableData: [],
      clickData: [],
      totalPage: 0,
      pageSize: 10,
      pageIndex: 1,
      listLoading: false,
      resetDataForm: {
        donePwd: '',
        pwd: ''
      },
      code: '',
      rules: {
        pwd: [
            { validator: validatePass, trigger: 'change', require: true },
            { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        donePwd: [
            { validator: validatePass2, trigger: 'change', require: true },
            { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ]
      },
      // clickData: [
      //   {
      //     name: '编辑',
      //     type: 'edit'
      //   }, {
      //     name: '删除',
      //     type: 'delete'
      //   },
      //   {
      //     name: '重置密码',
      //     type: 'resetPwd'
      //   }
      //  ],
      tableHeaders: [
        { headerKey: 'username', headerName: '登录名称' },
        { headerKey: 'realName', headerName: '真实姓名' },
        { headerKey: 'mail', headerName: '电子邮箱' },
        { headerKey: 'phone', headerName: '电话' },
        // { headerKey: 'orgName', headerName: '组织机构名称' },
        // { headerKey: 'companyName', headerName: '公司名称' },
        { headerKey: 'lastLoginTime', headerName: '最后登录时间', width: '160' },
        { headerKey: 'remark', headerName: '备注' }
        // { headerKey: 'isEffect', headerName: '是否有效' }
      ],
      queryMap: [
        {
          headerKey: 'isEffect',
          headerName: '是否有效',
          fun (row) {
            if (row.isEffect) {
              return '有效'
            } else if (!row.isEffect) {
              return '无效'
            } else {
              return '-'
            }
          }
        }
      ]
    }
  },
  mounted: function () {
    this.clickData = this.$showBtn([
      { btnName: 'USER_EDIT', name: '编辑', type: 'edit' },
      { btnName: 'USER_DEL', name: '删除', type: 'delete' },
      { btnName: 'USER_RESET', name: '重置密码', type: 'resetPwd' }
    ])
    this.getList()
    // document.onkeydown = e => {
    //   var key = window.event.keyCode
    //   if (key == 13) {
    //     this.getList(1)
    //   }
    // }
  },
  methods: {
    onReset () {
      this.queryDataForm.username = ''
      this.queryDataForm.companyName = ''
      this.getList('noPage')
    },
    clickRight (data) {
      if (data.type === 'edit') {
        this.edit(data.row)
      } else if (data.type === 'delete') {
        this.delUser(data.row.code)
      } else if (data.type === 'resetPwd') {
        this.resetPwd(data.row.code)
      }
    },
    resetPwd (code) {
      this.dialogVisible = true
      this.code = code
    },
    doneResetPwd (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          var data = {
            userCode: this.code,
            password: md5(this.resetDataForm.donePwd)
          }
          this.$http
              .post(
                `/${this.$const.PREFIX.AUTHORITY}/user/resetPassword`,
                data
              )
              .then(res => {
                if (res.result) {
                  this.$message({
                    message: '操作成功',
                    type: 'success'
                  })

                  this.dialogVisible = false
                  this.getList()
                } else {
                  this.$message.error({
                    message: res.msg,
                    duration: 5000
                  })
                }
              })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    add () {
      this.$router.push('/systemSettings/user/addUser')
    },
    edit (row) {
      this.$router.push({
        path: '/systemSettings/user/edit',
        query: { code: row.code }
      })
    },
    cancel () {
      this.dialogVisible = false
      this.isShowError = false
    },
    delUser (row) {
      this.$confirm('确认删除该条数据？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .post(`/${this.$const.PREFIX.AUTHORITY}/user/dels`, { codes: [row] })
          .then(res => {
            if (res.result) {
              this.queryDataForm.page = 1
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.getList()
            } else {
              this.$message.error({
                message: res.msg,
                duration: 5000
              })
            }
          })
      })
    },
    getList (type) {
      this.queryDataForm.username = this.queryDataForm.username.trim()
      if (type && type === 'noPage') {
        this.queryDataForm.page = 1
      }
      this.$http
        .post(
          `/${this.$const.PREFIX.AUTHORITY}/user/findAllUserByConditons`,
          this.queryDataForm
        )
        .then(res => {
          console.log(res)
          var backData = res.data
          if (res.result) {
            this.totalPage = backData.total
            this.tableData = backData.records
          } else {
            this.$message.error({
              message: res.msg,
              duration: 5000
            })
          }
        })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.queryDataForm.size = val
      this.queryDataForm.page = 1
      this.getList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.queryDataForm.page = val
      this.getList()
    },
    delQueryModel () {}
  }
}
</script>
<style >
.change-pwd  {
  position: relative;
}
.change-pwd .el-form-item__label:before{
content: ''!important;
    color: #fff;
    margin-right: 4px;
}
.change-pwd input {
 height: 38px!important;
 width: 272px;
 border:1px solid #d2d2d2!important;
}
.change-title  .el-dialog__title {
  font-weight: 600!important;
}
.change-pwd input:focus {
  border:1px solid #1868b3!important;
 
}
.change-pwd button {
  height: 40px;
  width: 102px;
}
.change-pwd button:nth-child(1) {
  margin-left: 26px;
}
.change-pwd button:nth-child(1):hover，.change-pwd button:nth-child(1):active,.change-pwd button:nth-child(1):focus {
  background: #1868b3!important;
}
.change-pwd button.el-button--primary:focus {
   background: #1868b3!important;
}
.change-pwd button.el-button--default {
  background: #d1d9e0!important;
  color: #fff!important;
}
</style>
